//
//  EmoticonView.swift
//  表情键盘
//
//  Created by 吴婷婷 on 15/11/14.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit

private let EmoticonViewCellId = "EmoticonViewCellId"

class EmoticonView: UIView {
    /// 选中表情回调
    private var selectedEmoticonCallBack: (emoticon: Emoticon)->()
    
    //MARK: - toolbar上按钮的监听方法
    func clickItem(item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    //MARK: - 构造函数
    
    init(selectedEmoticon: (emoticon: Emoticon)->()) {
        self.selectedEmoticonCallBack = selectedEmoticon
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        super.init(frame: rect)
        
        setupUI()
        
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 懒加载控件
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonViewLayout())
    private lazy var toolbar = UIToolbar()
    //表情包数组
    private lazy var packages = EmoticonManager.sharedManager.packages
    
}
//MARK: - 设置界面
private extension EmoticonView {
    func setupUI() {
        addSubview(collectionView)
        addSubview(toolbar)
        
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolbar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
        prepareToolbar()
        prepareCollectionView()
    }
    
    func prepareToolbar() {
        tintColor = UIColor.darkGrayColor()
        
        var items = [UIBarButtonItem]()
        var index = 0
        
        for p in packages {
            let item = UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self, action: "clickItem:")
            item.tag = index++
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
    }
    
    func prepareCollectionView() {
        
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellId)
        collectionView.backgroundColor = UIColor.whiteColor()
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
     ///表情键盘视图布局
    private class EmoticonViewLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            
            let w = collectionView!.bounds.width / col
            let margin = (collectionView!.bounds.height - row * w) * 0.5
            
            itemSize = CGSize(width: w, height: w)
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            scrollDirection = .Horizontal
            collectionView?.bounces = false
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            
            
        }
    }
    
}
//MARK: - 数据源方法,代理方法
extension EmoticonView: UICollectionViewDataSource , UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let em = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack(emoticon: em)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let emoticon = packages[indexPath.section].emoticons[indexPath.item]
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellId, forIndexPath: indexPath) as! EmoticonViewCell
        
        cell.emoticon = emoticon
//        cell.emoticonButton.setTitle(String(indexPath.item), forState: .Normal)
        
        cell.backgroundColor = UIColor.lightGrayColor()
        
        return cell
    }
    
}
//MARK: - 表情cell
private class EmoticonViewCell: UICollectionViewCell {
    /// 表情模型
    var emoticon: Emoticon? {
        didSet {
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            emoticonButton.userInteractionEnabled = false
            
            // 设置删除按钮
            if emoticon!.isRemoved {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    
    //MARK: - 构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //MARK: - 懒加载控件
    lazy var emoticonButton: UIButton = UIButton()
}





